package com.example.foodwebbackend.service;

import com.example.foodwebbackend.dto.PageRequest;
import com.example.foodwebbackend.dto.PageResponse;
import com.example.foodwebbackend.dto.UserRequest;
import com.example.foodwebbackend.entity.User;
import com.example.foodwebbackend.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 用户注册
     */
    public User register(String username, String password) {
        // 检查用户名是否已存在
        if (userMapper.existsByUsername(username)) {
            throw new RuntimeException("用户名已存在");
        }

        // 创建新用户
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setAvatarPath("/businessmen.png");
        user.setRegisterTime(LocalDateTime.now());

        userMapper.insert(user);
        return user;
    }

    /**
     * 用户登录验证
     */
    public User login(String username, String password) {
        User user = userMapper.findByUsername(username);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        if (!password.equals(user.getPassword())) {
            throw new RuntimeException("密码错误");
        }

        // 更新最后登录时间
        userMapper.updateLastLoginTime(user.getUserId());

        return user;
    }

    /**
     * 根据用户名查找用户
     */
    public User findByUsername(String username) {
        return userMapper.findByUsername(username);
    }

    /**
     * 根据用户ID查找用户
     */
    public User findById(Integer userId) {
        return userMapper.findById(userId);
    }

    /**
     * 更新用户信息
     */
    public User updateUser(User user) {
        if (user.getPassword() != null && !user.getPassword().isEmpty()) {
            user.setPassword(user.getPassword());
        }
        userMapper.update(user);
        return userMapper.findById(user.getUserId());
    }

    /**
     * 删除用户
     */
    public void deleteUser(Integer userId) {
        userMapper.deleteById(userId);
    }

    /**
     * 获取所有用户
     */
    public List<User> getAllUsers() {
        return userMapper.findAll();
    }

    /**
     * 检查用户名是否存在
     */
    public boolean existsByUsername(String username) {
        return userMapper.existsByUsername(username);
    }

    /**
     * 统计用户总数
     */
    public int countUsers() {
        return userMapper.countUsers();
    }

    /**
     * 分页获取用户列表
     */
    public PageResponse<User> getUsersWithPagination(PageRequest pageRequest) {
        List<User> users = userMapper.findUsersWithPagination(pageRequest);
        long total = userMapper.countUsersWithSearch(pageRequest.getSearch());
        return new PageResponse<>(users, pageRequest.getPage(), pageRequest.getSize(), total);
    }

    /**
     * 创建用户
     */
    public User createUser(UserRequest request) {
        User user = new User();
        user.setUsername(request.getUsername());
        user.setPassword(request.getPassword());
        user.setAvatarPath(request.getAvatarPath() != null ? request.getAvatarPath() : "/businessmen.png");
        user.setRegisterTime(LocalDateTime.now());
        
        userMapper.insert(user);
        return user;
    }

    /**
     * 更新用户
     */
    public User updateUser(Integer userId, UserRequest request) {
        User user = userMapper.findById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        if (request.getUsername() != null) {
            user.setUsername(request.getUsername());
        }
        if (request.getPassword() != null && !request.getPassword().trim().isEmpty()) {
            user.setPassword(request.getPassword());
        }
        if (request.getAvatarPath() != null) {
            user.setAvatarPath(request.getAvatarPath());
        }
        
        userMapper.update(user);
        return userMapper.findById(userId);
    }

    /**
     * 批量删除用户
     */
    public int batchDeleteUsers(List<Integer> userIds) {
        return userMapper.batchDeleteByIds(userIds);
    }

    /**
     * 重置密码
     */
    public void resetPassword(Integer userId, String newPassword) {
        User user = userMapper.findById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        user.setPassword(newPassword);
        userMapper.update(user);
    }
} 